package com.wl.api.controller.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wl.api.common.utils.WebUtil;
import com.wl.api.filter.autentication.AuthorizeStatus;

import lombok.extern.log4j.Log4j;

@ControllerAdvice
@Log4j
public class GlobalExceptionHandler {
	 
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public AuthorizeStatus jsonErrorHandler(HttpServletRequest req,HttpServletResponse response, Exception e) throws Exception {
	log.error("url:" +req.getRequestURI() + " req param:" +  WebUtil.getParameters(req).toString());
	log.error(responseStack(e.getStackTrace()));
	log.error(e.getMessage());
	/*response.setCharacterEncoding("UTF-8");  
	response.setContentType("application/json; charset=utf-8");
	 PrintWriter writer= response.getWriter();
	 
	 if (e instanceof AuthorizeException) {
		 response.setStatus(401);
		 writer.write(JSON.toJSONString(respMes(401, "unauthorized login !", req.getRequestURI())));
	 } else {
	 	response.setStatus(400);
		 writer.write(JSON.toJSONString(respMes(400, "bad request!", req.getRequestURI())));
	 }

	 writer.flush();
	 writer.close();*/
	
	return new AuthorizeStatus("400", req.getRequestURI(), "bad request");
	}
	
	
	private String responseStack(StackTraceElement[] stack) {
		StringBuffer sb = new StringBuffer();
		if (stack != null) {
			for(int i =0 ; i < stack.length ; i++) {
				sb.append(stack[i].toString()+"; ");
			}
		}
		return sb.toString();
	}
}
